package com.dmai.aiet.epc.archive.config;

import cn.hutool.core.convert.Convert;
import com.dmai.aiet.epc.archive.properties.TraceProperties;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Type;

@Slf4j
//@Component
//@ConditionalOnClass({HttpServletRequest.class})
//@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class WebLogBodyAdvice extends RequestBodyAdviceAdapter implements ResponseBodyAdvice<Object> {

    @Resource
    private HttpServletRequest request;
    @Resource
    private TraceProperties traceProperties;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return Convert.toBool(traceProperties.getEnable(), false);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return Convert.toBool(traceProperties.getEnable(), false);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
        printLogTable(request,response, body);
        return body;
    }

    private void printLogTable(ServerHttpRequest request,ServerHttpResponse response,Object obj) {
        try {
            log.info("request:{}, response:{}",request.getURI().getRawPath(),((ServletServerHttpResponse) response).getServletResponse().getStatus());

        } catch (Exception e) {
            log.error("记录异常", e);
        }
    }
}
